'use client'
import React, { useState, useEffect } from 'react'
import { AudioOutlined, CloseOutlined } from '@ant-design/icons'
import { Input, Space, Button } from 'antd'
import type { GetProps } from 'antd'
import { useRouter, useSearchParams } from 'next/navigation'

type SearchProps = GetProps<typeof Input.Search>
const { Search } = Input

interface SearchBarProps {
  width?: number | string
  defaultValue?: string
  targetPath: string
  placeholder: string
  clearAfterSearch?: boolean
  ignoreUrlParams?: boolean
}

export default function SearchBar({
  width = 400,
  defaultValue = '',
  targetPath,
  placeholder,
  clearAfterSearch = false,
  ignoreUrlParams = false,
}: SearchBarProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [searchValue, setSearchValue] = useState(defaultValue)

  // 只有非Header的搜索框才读取URL参数（忽略Header的）
  useEffect(() => {
    if (!ignoreUrlParams) {
      const keyword = searchParams.get('condition.keyword') || ''
      setSearchValue(keyword)
    }
  }, [searchParams, targetPath, ignoreUrlParams]) // 依赖新增ignoreUrlParams

  const onSearch: SearchProps['onSearch'] = value => {
    const trimmedValue = value.trim()
    const url = new URL(targetPath, window.location.origin)

    if (trimmedValue) {
      url.searchParams.set('condition.keyword', trimmedValue)
    } else {
      url.searchParams.delete('condition.keyword')
    }

    router.push(url.pathname + url.search)
    if (clearAfterSearch) {
      setSearchValue('')
    }
  }

  const handleClear = () => {
    setSearchValue('')
    onSearch('')
  }

  return (
    <Space direction="vertical">
      <Search
        placeholder={placeholder}
        enterButton="查一下"
        size="large"
        suffix={
          searchValue ? (
            <Button
              icon={<CloseOutlined />}
              onClick={handleClear}
              size="small"
              type="text"
              style={{ color: '#999', marginLeft: 8 }}
            />
          ) : (
            <AudioOutlined style={{ fontSize: 16, color: '#1677ff' }} />
          )
        }
        onSearch={onSearch}
        style={{ width }}
        value={searchValue}
        onChange={e => setSearchValue(e.target.value)}
        onPressEnter={e => onSearch(e.target.value)}
      />
    </Space>
  )
}
